<template>
  <section>
  <el-dialog :visible.sync="dialogProps.visible" width="560px" v-loading="showLoading" @open="handleDialogOpen()">
    <div slot="title" class="dialog-header"><h3>{{ dialogProps.title }}</h3></div>
    <el-form class="form" :model="channelGroup" :rules="formRules" 
      ref="channelGroupForm" label-width="80px" label-position="right" size="small">
      <el-form-item label="群组名称" prop="groupName">
        <el-col :span="16"><el-input ref="channelGroupName" size="small" :maxlength="64" v-model="channelGroup.groupName" autofocus="autofocus" @focus="clearValidate"></el-input></el-col>
      </el-form-item>
      <el-form-item label="群组备注" prop="remark">
        <el-col :span="16">
          <el-input type="textarea" :rows="3" v-model="channelGroup.remark">
          </el-input>          
        </el-col>
      </el-form-item>
      <el-form-item label="成员">
        <el-col :span="16">
 			<el-tag
			  :key="user.userid"
			  v-for="(user,index) in channelGroup.users"
			  closable
			  :disable-transitions="false"
			  @close="unselectUser(user,index)">
			  {{user.username}}
			</el-tag> 
			<el-button  class="button-new-tag" size="small" @click="showUsersSelectDlg">+ 新成员</el-button>
        </el-col>
      </el-form-item>
    </el-form>

   
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="doCloseDialog()">取 消</el-button>
      <el-button type="primary" size="small" @click="doSaveChannelGroup()">确 定</el-button>
    </span>
  </el-dialog>
    			<!--选中更多用户-->
	<el-dialog title="选择更多用户" :visible.sync="usersSelectVisible"  width="70%"  :close-on-click-modal="false" append-to-body>
		  <users-select :selected-users="channelGroup.users" :visible="usersSelectVisible" @cancel="usersSelectVisible=false" @confirm="afterUsersSelectConfirm"></users-select>
	</el-dialog>
  </section>
</template>

<script>
import seq from '@/common/js/sequence';//全局公共库
import { createChannel } from '@/api/channel'
import { listUser } from '@/api/user'
import UsersSelect from '../../sys/user/UsersSelect.vue'; 
import { mapGetters } from 'vuex'

export default { 
  name: "create-channel-group",
  props:['categoryId'],//需要传入分组类型 css 客服、
  computed: { 
	    ...mapGetters([
	      'userInfo','token'
	    ])
  },
  data() {
    return {
      showLoading: false,
      dialogProps: {
        visible: false,
        action: '',
        title: ''
      },
      channelGroup : {
        groupName: '',
        categoryId: '',
        cuserid:'',
        cusername:'',
        bizStatus:'',
        gstatus:'1',
        shopId:'',
        locationId:'',
        branchId:'',
        allowJoin:'1',
        needAudit:'0',
        headimgurl:'',
        isPrichat:'0', 
        users: [], 
      },
      searchParams: {
        username: '',
        limit: 20,
        offset: 0
      },  
      usersSelectVisible:false, 
      userTotal: 0,
      formRules: {
        name: [
          { required: true, message: '请输入群组名称', trigger: 'blur' },
          { min: 3, max: 64, message: '长度在 3 到 64 个字符', trigger: 'blur' }
        ],
      }      
    }
  },
  methods: {
    doCloseDialog() {
      Object.assign(this.$data, this.$options.data())
      this.dialogProps.visible = false
    },
    showUsersSelectDlg(){
    	this.usersSelectVisible=true;
    },
    clearValidate() {
      this.$refs['channelGroupForm'].clearValidate()
    },
    afterUsersSelectConfirm: function(users){
    	console.log('xxxxxxxxxxxxxxxxxxxxxx')
    	console.log(users)
    	users.forEach(user=>{
    		if(!this.channelGroup.users.some(i=>i.userid==user.userid)){
    			this.channelGroup.users.push(Object.assign({},user))
    		}
    	})
    	if(this.channelGroup.groupName==''||this.channelGroup.groupName.indexOf(this.userInfo.username)==0){
    		var users=this.channelGroup.users;
    		var groupName='';
    		if(users.length>3){
    			groupName=users[0].username+','+users[1].username+','+users[2].username
    		}else{
    			groupName=users.map(i=>i.username).join(",");
    		}
    		this.channelGroup.groupName=groupName+"等参与的群聊"
    	}
      this.usersSelectVisible=false;
      this.dialogProps.visible=true;
    },
    handleDialogOpen() {
      this.$nextTick(() => {
        this.$refs['channelGroupForm'].clearValidate()
        this.$refs['channelGroupName'].focus()
      })
    },
    getUsers() {
      this.showLoading = true
      listUser(this.searchParams.username, this.searchParams.limit, this.searchParams.offset)
      .then(response => {
        let users = []
        for(let user of response.data.rows) {
          if(user.id !== this.userInfo.userid) {
            users.push({
              id: user.id,
              nickname: user.nickname
            })
          }
        }
        this.users = [...this.users, ...users]
        this.userTotal = response.data.total
        this.showLoading = false
      })
      .catch(error => {
        this.showLoading = false
        //outputError(this, error)
      })      
    },
    selectUser(user, index) {
      this.channelGroup.users.push(
        {
          id: user.id,
          nickname: user.nickname,
          index: index
        }
      )
      this.users.splice(index, 1)
    },
    unselectUser: function(user,index) {
    	console.log(user)
      if(user.userid !== this.userInfo.userid) {   
            this.channelGroup.users.splice(index, 1); 
      }
    	if(this.channelGroup.groupName==''||this.channelGroup.groupName.indexOf(this.userInfo.username)==0){
    		var users=this.channelGroup.users;
    		var groupName='';
    		if(users.length>3){
    			groupName=users[0].username+','+users[1].username+','+users[2].username
    		}else{
    			groupName=users.map(i=>i.username).join(",");
    		}
    		this.channelGroup.groupName=groupName+"等参与的群聊"
    	}
    },
    loadMoreUser() {
      this.searchParams.offset += this.searchParams.limit
      this.getUsers()
    },
    doSaveChannelGroup() {
      this.$refs['channelGroupForm'].validate(valid => {
        if (valid) {  
          this.channelGroup.groupId=seq.sn();
          if(this.categoryId!=''&&this.categoryId!=null){
            this.channelGroup.categoryId=this.categoryId
          }
            this.$emit('onChannelGroupCreate',this.channelGroup)
            this.showLoading = false
            Object.assign(this.$data, this.$options.data())
            this.dialogProps.visible = false
        }
      })
    },
    doSearchUser() {
      this.users = []
      this.getUsers()
    },
    onSearchInputKeyUp(event) {
      if(event.keyCode === 13) {
        this.users = []
        this.getUsers()
      }
    }     
  },
  watch: {
    'searchParams.username': function(newVal, oldVal) {
      if(newVal.trim() === '') {
        //this.doSearchUser()
      }
    }
  },  
	components: {  
	    'users-select':UsersSelect,  
	    //在下面添加其它组件
	},
  mounted: function() {
    this.$nextTick(() => {  
      this.$on('openDialog', function(action) {
        
        //this.getUsers()
        if(action!=='add'){
        	this.getUsers()
        }else{
        	this.channelGroup={groupId:'',groupName:'',cuserid:this.userInfo.userid,cusername:this.userInfo.username,cheadimgurl:this.userInfo.headimgurl,users:[]} 
            this.channelGroup.users.push({
                userid: this.userInfo.userid,
                username: this.userInfo.username,
                headimgurl:this.userInfo.headimgurl
              })
              
              this.dialogProps.title = action === 'add' ? '添加群聊' : '修改群聊'
              	this.$nextTick(() => {  
                      if(action==='add'){
                      	this.usersSelectVisible=true;
                      }else{
                        this.dialogProps.visible = true
                      }
          	})
        }

      })
    })


  }
}
</script>

<style lang="scss" scoped>
.form {
  padding: 2px 0 0 16px;
  border-bottom: solid 1px #F0EEEA;
}
.user-list-container {
  border: solid 1px #D4D1CC;
  width: 48%;
  .title {
    height: 32px;
    text-align: center;
    font-weight: bold;
    background-color: #F0F0F0;
    border-bottom: solid 1px #F0F0F0;
  }
  .search-container {
    text-align: center;
    padding: 0;
    margin: 0;
    border-bottom: solid 1px #F0F0F0;
    input {
      margin: 0 0 0 4px;
      height: 22px;
      line-height: 22px;
      width: 110px;
      outline: 0;
      border: none;
      background-color: transparent;
      -webkit-appearance: textfield;
      -webkit-rtl-ordering: logical;
      cursor: text;
    }
    i {
      cursor: pointer;
      height: 22px;
      line-height: 22px;
    }    
    input::-webkit-input-placeholder {
      color: #DDDBD7;
    }
    input::-moz-placeholder {   /* Mozilla Firefox 19+ */
      color: #DDDBD7;
    }
    input:-moz-placeholder {    /* Mozilla Firefox 4 to 18 */
      color: #DDDBD7;
    }
    input:-ms-input-placeholder {  /* Internet Explorer 10-11 */ 
      color: #DDDBD7;
    }      
  }
  ul {
    padding: 0;
    margin: 0;
    overflow-y: auto;
    list-style-type: none;
    .load-more {
      text-align: center;
      font-size: 11px;
    }
    li {
      display: list-item;
      padding: 0 5px;
      margin: 0;
      span {
        font-weight: bold;
        float: right;
        display: none;
      }
    }
    li:hover {
      background-color: #F1EFEE;
      cursor: pointer;
    }
    li:hover span {
      display: block;
    }    
  }
}
.left-list {
  float: left;
  ul {
    height: 200px;
  }
}
.right-list {
  float: right;
  ul {
    height: 232px;
  }  
}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  } 
</style>